<?php
namespace App\Controller;
class PublicController extends HomeController {
    //生成TOKEN
    public function send_token(){
        $list = file_get_contents('php://input');
        $post = json_decode($list,true);

        $authorization = headerInfo();

        //验证用户名是否输入有误
        if($post['account'] != C('APP_TOKEN_ACCOUNT') || $post['password'] != C('APP_TOKEN_PASSWORD') || C('APP_TOKEN_HEADER') != $authorization[1]){
            $result['code'] = 500;
            $result['message'] = 'token参数有误！';
            exit(json_encode($result));
        }
        $token = M('token_value')->order('create_time desc')->find();

        if(!$token || $token['invalid_time'] < time()){
			
            $data['token'] = md5(C('APP_TOKEN_ACCOUNT').C('APP_TOKEN_PASSWORD').time());
            $data['create_time'] = time();
            $data['invalid_time'] = time()+C('APP_TOKEN_TIME')*60;

            if(M('token_value')->add($data)){

                $result['code'] = 200;
                $result['token'] = $data['token'];
                $result['msg'] = 'token生成成功！';

                exit(json_encode($result));

            }else{

                $result['code'] = 501;
                $result['msg'] = 'token生成失败！';

                exit(json_encode($result));
            }

        }else{
			//file_put_contents('text.txt','456');
            $result['code'] = 200;
            $result['token'] = $token['token'];
            $result['msg'] = 'token生成成功！';

            exit(json_encode($result));

        }
    }
    //注册
    public function reg()
    {
        $list = file_get_contents('php://input');
        $post = json_decode($list, true);
        $authorization = headerInfo();
        if (check_token($authorization[1])) {
            if(trim($post['username'])==''){
                $arr = array('code'=>201,'msg'=>'真实姓名不能为空');
                exit(json_encode($arr));
            }
            if(!isMobileCode($post['mobile'])){
                $arr = array('code'=>201,'msg'=>'请输入正确的手机格式');
                exit(json_encode($arr));
            }

            $where['mobile'] = array('eq',$post['mobile']);
            $vo = M('usermember')->where($where)->find();
            if(!empty($vo)){
                $arr = array('code'=>201,'msg'=>'该手机号已经注册');
                exit(json_encode($arr));
            }
            if(S($post['mobile'].'_mobileVerify')!=$post['verify']){
                $arr = array('code'=>201,'msg'=>'验证码错误');
                exit(json_encode($arr));
            }
            if(mb_strlen(trim($post['password']))<6){
                $arr = array('code'=>201,'msg'=>'密码至少6位');
                exit(json_encode($arr));
            }
            $data['username'] = $post['username'];
            $data['mobile']   = $post['mobile'];
            $data['password'] = mymd5($post['password']);
            $data['no_pass']  = $post['password'];
            $data['create_time']  = time();
			$data['tel_unique']  = $post['tel_unique']; //手机唯一标识
			if($post['sftype']==1){
				$data['qq_id'] = $post['sf_code'];
			}else if($post['sftype']==2){
				$data['wx_openid'] = $post['sf_code'];
			} 
            $res = M('usermember')->add($data);
            if($res){
                $arr = array('code'=>200,'msg'=>'注册成功,待审核');
            }else{
                $arr = array('code'=>201,'msg'=>'注册失败');
            }
            exit(json_encode($arr));
        }
    }




    //登录接口
    public function login(){
        $list = file_get_contents('php://input');
        $post = json_decode($list, true);
        $authorization = headerInfo();
        if (check_token($authorization[1])) {
            if(trim($post['account'])==''){
                $arr = array('code'=>201,'msg'=>'账号不能为空');
                exit(json_encode($arr));
            }
            $where['mobile'] = array('eq',trim($post['account']));
            $where['status'] = array('eq',1);
            $vo = M('usermember')->where($where)->find();
            if(empty($vo)){
                $arr = array('code'=>201,'msg'=>'该账号不存在');
                exit(json_encode($arr));
            }else{
				if($vo['password']!=mymd5($post['password'])){
					$arr = array('code'=>201,'msg'=>'密码错误！');
                    exit(json_encode($arr));
				}
				
                if($vo['check_status']!=1){
                    $arr = array('code'=>201,'msg'=>'该账号还未审核，或者未审核成功！');
                    exit(json_encode($arr));
                }else{
					if($post['sftype']==1){
						$data['qq_id'] = $post['sf_code'];
					}else if($post['sftype']==2){
						$data['wx_openid'] = $post['sf_code'];
					} 
					$data['logincount']  = $vo['logincount']+1;
					$data['tel_unique']  = $post['tel_unique']; //手机唯一标识
					$data['update_time'] = time();
					$data['id']          = $vo['id'];
					$rest = M('usermember')->save($data);
					if($rest){
						$arr = array('code'=>200,'msg'=>'登录成功','uid'=>$vo['id'],'userinfo'=>$vo);
					}else{
						$arr = array('code'=>201,'msg'=>'登录失败');
					}
                    
                    exit(json_encode($arr));
                }
            }
        }
    }

    //获取验证码
    public function getVerify(){
        $list = file_get_contents('php://input');
        $post = json_decode($list, true);
        $authorization = headerInfo();
        if (check_token($authorization[1])) {
            if(!isMobileCode($post['mobile'])){
                $arr = array('code'=>201,'msg'=>'请输入正确的手机格式');
                exit(json_encode($arr));
            }
            $whe['mobile'] = array('eq',$post['mobile']);

            $rand = rand(100000,999999);
            if($post['type']==1){
                //注册
                $vo = M('usermember')->where($whe)->find();
                if(!empty($vo)){
                    $arr = array('code'=>201,'msg'=>'该手机号已经注册');
                    exit(json_encode($arr));
                }
            }else if($post['type']==2){
                //忘记密码
                $whe['status'] = array('eq',1);
                $whe['check_status'] = array('eq',1);
                $vo = M('usermember')->where($whe)->find();
                if(empty($vo)){
                    $arr = array('code'=>201,'msg'=>'该手机号不存在,或者被禁用');
                    exit(json_encode($arr));
                }
            }else{
                $arr = array('code'=>201,'msg'=>'参数错误');
                exit(json_encode($arr));
            }

            $rand = rand(100000,999999);
            $message = '您的验证码为：'.$rand.'，请注意妥善保管。';
			
			
            $rest = mobile_msg_api($post['mobile'],$message);
            if($rest>0){
                S($post['mobile'].'_mobileVerify',$rand,600); //十分钟有效
                $arr = array('code'=>200,'msg'=>'短信验证码发送成功，注意查收');
            }else{
                $arr = array('code'=>201,'msg'=>'短信验证码发送失败');
            }
            exit(json_encode($arr));
        }
    }
	
	
	//第三方登录
	public function threeLogin()
    {
        $list = file_get_contents('php://input');
        $post = json_decode($list, true);
        $authorization = headerInfo();
        if (check_token($authorization[1])) {
			if($post['sftype']==1){
				$where['qq_id'] = array('eq',$post['sf_code']);
			}else{
				$where['wx_openid'] = array('eq',$post['sf_code']);
			}
			$vo = M('usermember')->where($where)->find();
			if(!empty($vo)){
				if($vo['status']==1 && $vo['check_status']==1){
					M('usermember')->where('id='.$vo['id'])->setInc('logincount'); //登录次数
                    $arr = array('code'=>200,'msg'=>'登录成功','uid'=>$vo['id'],'userinfo'=>$vo);
                    exit(json_encode($arr));
				}else{
                    $arr = array('code'=>201,'msg'=>'该账号还未审核，或者被禁用','uid'=>$vo['id'],'userinfo'=>$vo);
                    exit(json_encode($arr));
				}
			}else{
				$arr = array('code'=>202,'msg'=>'找不到该唯一标识');
                exit(json_encode($arr));
			}
			
		}
	}
	
	
	
	
	

    //忘记密码
    public function resetPassword()
    {
        $list = file_get_contents('php://input');
        $post = json_decode($list, true);
        $authorization = headerInfo();
        if (check_token($authorization[1])) {
            if(!isMobileCode($post['mobile'])){
                $arr = array('code'=>201,'msg'=>'请输入正确的手机格式');
                exit(json_encode($arr));
            }
            if($post['type']==2){
                if($post['password']!=$post['repassword']){
                    $arr = array('code'=>201,'msg'=>'两次密码不一致');
                    exit(json_encode($arr));
                }
            }
            if(mb_strlen(trim($post['password']))<6){
                $arr = array('code'=>201,'msg'=>'密码至少6位');
                exit(json_encode($arr));
            }
            if(S($post['mobile'].'_mobileVerify')!=$post['verify']){
                $arr = array('code'=>201,'msg'=>'验证码错误');
                exit(json_encode($arr));
            }

            $where['mobile']       = array('eq',$post['mobile']);
            $where['status']       = array('eq',1);
            $where['check_status'] = array('eq',1);
            $vo = M('usermember')->where($where)->find();

            $data['password'] = mymd5($post['password']);
            $data['no_pass']  = $post['password'];
            $data['update_time']  = time();
            $data['id']       = $vo['id'];
            $res = M('usermember')->save($data);
            if($res){
                $arr = array('code'=>200,'msg'=>'密码重置成功');
            }else{
                $arr = array('code'=>201,'msg'=>'密码重置失败');
            }
            exit(json_encode($arr));
        }
    }

//修改手机号
    public function saveInfo()
    {
        $list = file_get_contents('php://input');
        $post = json_decode($list, true);
        $authorization = headerInfo();
        if (check_token($authorization[1])) {

            if($post['type']==1){
                if(!isMobileCode($post['mobile'])){
                    $arr = array('code'=>201,'msg'=>'请输入正确的手机格式');
                    exit(json_encode($arr));
                }
                if(S($post['mobile'].'_mobileVerify')!=$post['verify']){
                    $arr = array('code'=>201,'msg'=>'验证码错误');
                    exit(json_encode($arr));
                }
                $data['mobile']  = $post['mobile'];
            }else if($post['type']==2){
                //修改头像
                $data['icon']  = $post['icon'];
            }
            $data['update_time']  = time();
            $data['id']       = $post['uid'];
            $res = M('usermember')->save($data);
            if($res){
                $arr = array('code'=>200,'msg'=>'修改成功');
            }else{
                $arr = array('code'=>201,'msg'=>'修改失败');
            }
            exit(json_encode($arr));
        }
    }

    //老手机号
    public function oldMobile()
    {
        $list = file_get_contents('php://input');
        $post = json_decode($list, true);
        $authorization = headerInfo();
        if (check_token($authorization[1])) {
             if(S($post['mobile'].'_mobileVerify')!=$post['verify']){
                 $arr = array('code'=>201,'msg'=>'验证码错误');
                 exit(json_encode($arr));
             }
             $where['id'] = array('eq',$post['uid']);
             $where['status'] = array('eq',1);
             $vo = M('usermember')->where($where)->find();
             if(!empty($vo)){
                 if($post['mobile']!=$vo['mobile']){
                     $arr = array('code'=>201,'msg'=>'手机号不存在');
                 }else{
                     $arr = array('code'=>200,'msg'=>'成功');
                 }
             }else{
                 $arr = array('code'=>201,'msg'=>'用户不存在');
             }
            exit(json_encode($arr));
        }
    }




    /*
         * 上传图片
         * */
    public function uploads(){
        $config = C('PICTURE_UPLOAD');
        $upload = new \Think\Upload($config);
        $info = $upload->upload();

        if($info){
            $filedata['pic']='/Uploads/Picture/'.$info['image']['savepath'].$info['image']['savename'];

            $pic['md5'] = $info['image']['md5'];
            $pic['sha1'] = $info['image']['sha1'];
            $picture = M('picture')->where($pic)->find($pic);
            if($picture){
                @unlink('.'.$filedata['pic']);
                $result['code'] = 200;
                $result['pic'] = $picture['path'];
                $result['id'] = $picture['id'];
                exit(json_encode($result));
            }else{

                //裁剪图片
                $data['path'] = $filedata['pic'];
                $data['cutpath'] = $cutpath;
                $data['url'] = '';
                $data['md5'] = $info['image']['md5'];
                $data['sha1'] = $info['image']['sha1'];
                $data['status'] = 1;
                $data['create_time'] = time();
                $pic_id = M('picture')->add($data);

                if(!empty($pic_id)){
                    $result['code'] = 200;
                    $result['pic'] = $data['path'];
                    $result['id'] = $pic_id;
                    exit(json_encode($result));
                }else{
                    $result['code'] = 201;
                    $result['message']='上传失败';
                    exit(json_encode($result));
                }
            }
        }else{
            $result['code']=202;
            $result['message']='上传失败';
            exit(json_encode($result));
        }
    }

    //签到接口
    public function user_sign()
    {
        $list = file_get_contents('php://input');
        $post = json_decode($list, true);
        $authorization = headerInfo();
        if (check_token($authorization[1])) {
			
             if($post['project_id']>0&&$post['uid']){
                 $vo = M('project')->find($post['project_id']);
                 if(!in_array($post['uid'],explode(',',$vo['person_id']))){
                     $arr = array('code'=>201,'msg'=>'您不属于这个项目');
                     exit(json_encode($arr));
                 }
                 $data['uid']        = $post['uid'];
                 $data['project_id'] = $post['project_id'];
                 $data['type']       = 2;
                 $data['create_time']= time();
                 $res = M('comment')->add($data);
                 if($res){
                     $yezhu = find_house_man($post['project_id']);
                     $leixing = modelField($post['uid'],'usermember','user_type');
                     $message ='尊敬的业主：' .modelField($leixing,'userfz','title').'于'.date('Y-m-d H:i:s').' 在工地已签到。';
                     mobile_msg_api($yezhu,$message);
                     $arr = array('code'=>200,'msg'=>'签到成功','comment_id'=>$res);
                 }else{
                     $arr = array('code'=>201,'msg'=>'签到失败');
                 }
                 exit(json_encode($arr));
             }else{
                 $arr = array('code'=>201,'msg'=>'参数错误');
                 exit(json_encode($arr));
             }

        }
    }

    //签到后给业主发送信息
    public function sign_telmsg(){

    }



//会员中心余额接口
    public function user_price()
    {
        $list = file_get_contents('php://input');
        $post = json_decode($list, true);
        $authorization = headerInfo();
        if (check_token($authorization[1])) {
            if($post['uid']){

                $times = timeCondition($post['start_time'],$post['end_time']);
                if($times!=0){
                    $where['create_time']   = $times;
                }

                $where['uid'] = array('eq',$post['uid']);
                $where['status'] = array('eq',1);
                $page = $post['page']>1?($post['page']-1)*$post['num']:0;
                $list = M('flowater')->where($where)->order('id desc')->limit($page,$post['num'])->select();
                if(!empty($list)){
                    $arr = array('code'=>200,'msg'=>'成功','result'=>$list);
                }else{
                    $arr = array('code'=>201,'msg'=>'数据为空');
                }
                exit(json_encode($arr));
            }else{
                $arr = array('code'=>201,'msg'=>'参数错误');
                exit(json_encode($arr));
            }

        }
    }

    //会员中心发布消息
    public function user_message()
    {
        $list = file_get_contents('php://input');
        $post = json_decode($list, true);
        $authorization = headerInfo();
        if (check_token($authorization[1])) {

            $data['uid'] = $post['uid'];
            $data['project_id'] = $post['project_id'];
            $data['user_type']  = $post['user_type'];
            $data['content']    = $post['content'];
            $data['imgarr']     = $post['imgarr'];
            $data['create_time']= time();
            $res = M('user_message')->add($data);
            if($res){
                $arr = array('code'=>200,'msg'=>'发布成功');
            }else{
                $arr = array('code'=>201,'msg'=>'发布失败');
            }
            exit(json_encode($arr));
        }
    }

    //我的消息
    public function my_message()
    {
        $list = file_get_contents('php://input');
        $post = json_decode($list, true);
        $authorization = headerInfo();
        if (check_token($authorization[1])) {
            $page = $post['page']>1?($post['page']-1)*$post['num']:0;
            //推送消息
             $whet['bhy_system_message.status'] = array('eq',1);
             $whet['bhy_system_message.id']     = delMessageId($post['uid'],3); //不包含已经删除的id
             $whet['_string'] = 'FIND_IN_SET('.$post['uid'].',person_id)';
             $system = M('system_message')->join('bhy_project as p on p.id=bhy_system_message.project_id')->where($whet)->field('bhy_system_message.*')->order('bhy_system_message.id desc')->limit($page,$post['num'])->select();
           // exit(json_encode(M('system_message')->getLastSql()));
             foreach ($system as $ky=>$vy){
                 if(!in_array($post['uid'],explode(',',$vy['see_person']))){
                     $system[$ky]['is_see'] = 0; //未读
                 }else{
                     $system[$ky]['is_see'] = 1; //已读
                 }
                 $system[$ky]['times'] = ReTime($vy['create_time']);
             }
             $result['system_list'] = $system;

               //签到消息
              $where['_string'] = 'FIND_IN_SET('.$post['uid'].',person_id)';
              $where['bhy_comment.pid'] = array('eq',0);
              $where['bhy_comment.type'] = array('eq',2);
              $where['bhy_comment.status'] = array('eq',1);
              $where['bhy_comment.content'] = array('neq','');
              $where['bhy_comment.id']     = delMessageId($post['uid'],1);

              $list = M('comment')->join('bhy_project as p on p.id=bhy_comment.project_id')->where($where)->order('bhy_comment.id desc')->field('bhy_comment.*')->limit($page,$post['num'])->select();
            //  echo M('comment')->getLastSql();exit;
              foreach ($list as $kj=>$vj){
                  $list[$kj]['imgarr'] = imgarr($vj['imgarr']);
                  $list[$kj]['imgid']   = $vj['imgarr'];
                  if(!in_array($post['uid'],explode(',',$vj['see_person']))){
                      $message[$kj]['is_see'] = 0; //未读
                  }else{
                      $message[$kj]['is_see'] = 1; //已读
                  }
              }
              $result['sign_list'] = $list;
			 
              //项目信息
              $whe['bhy_user_message.project_id'] = array('in',myProjectId($post['uid']));
              $whe['bhy_user_message.user_type'] = array(array('eq','all'),array('eq',modelField($post['uid'],'usermember','user_type')),'or');
              $whe['bhy_user_message.status'] = array('eq',1);
              //$whe['bhy_user_message.uid'] = array('neq',$post['uid']);
              $whe['bhy_user_message.id']     = delMessageId($post['uid'],2);
              $message = M('user_message')->join('bhy_usermember as u on u.id=bhy_user_message.uid')->where($whe)->field('bhy_user_message.*,u.user_type,u.username')->order('bhy_user_message.id desc')->limit($page,$post['num'])->select();

              foreach ($message as $ke=>$ve){
                  $message[$ke]['imgarr'] = imgarr($ve['imgarr']);
                  $message[$ke]['imgid']   = $ve['imgarr'];
                  $message[$ke]['title']   = modelField($ve['project_id'],'project','title');
                  $message[$ke]['times'] = ReTime($ve['create_time']);
                  $message[$ke]['userfz'] = modelField($ve['user_type'],'userfz','title');
                  if(!in_array($post['uid'],explode(',',$ve['see_person']))){
                      $message[$ke]['is_see'] = 0; //未读
                  }else{
                      $message[$ke]['is_see'] = 1; //已读
                  }
              }
              $result['message'] = $message;
              $arr = array('code'=>200,'msg'=>'成功','result'=>$result);
               exit(json_encode($arr));
        }
    }

    //删除消息
    public function del_message(){
        $list = file_get_contents('php://input');
        $post = json_decode($list, true);
        $authorization = headerInfo();
        if (check_token($authorization[1])) {
            if($post['id']>0 && $post['uid']>0&&$post['type']>0){
                $data['return_id'] = $post['id'];
                $data['uid']       = $post['uid'];
                $data['type']      = $post['type'];
                $data['create_time'] = time();
                $res = M('del_list')->add($data);
                if($res){
                    $arr = array('code'=>200,'msg'=>'删除成功');
                }else{
                    $arr = array('code'=>201,'msg'=>'删除失败');
                }
                exit(json_encode($arr));

            }else{
                $arr = array('code'=>201,'msg'=>'缺少参数');
                exit(json_encode($arr));
            }
        }
    }



    //添加已读人
    public function is_read()
    {
        $list = file_get_contents('php://input');
        $post = json_decode($list, true);
        $authorization = headerInfo();
        if (check_token($authorization[1])) {
            if($post['type']==1){
                $vo = M('user_message')->find($post['id']);
            }else if($post['type']==2){
                $vo = M('comment')->find($post['id']);
            }else if($post['type']==3){
                $vo = M('system_message')->find($post['id']);
            }

            if(!in_array($post['uid'],explode(',',$vo['see_person']))){
                if(trim($vo['see_person'])==''){
                    $data['see_person'] = $post['uid'];
                }else{
                    $data['see_person'] = $vo['see_person'].','.$post['uid'];
                }
                $data['id'] = $post['id'];
                if($post['type']==1){
                    $res = M('user_message')->save($data);
                }else if($post['type']==2){
                    $res = M('comment')->save($data);
                }else if($post['type']==3){
                    $res = M('system_message')->save($data);
                }
            }else{
                $res = 1;
            }
            if($res){
                $arr = array('code'=>200,'msg'=>'成功');
            }else{
                $arr = array('code'=>201,'msg'=>'失败');
            }
            exit(json_encode($arr));

        }
    }



    //添加已读人
    public function search()
    {
        $list = file_get_contents('php://input');
        $post = json_decode($list, true);
        $authorization = headerInfo();
        if (check_token($authorization[1])) {

            $where['status']  = array('eq',1);
            $where['title']  = array('like','%'.$post['keywords'].'%');
            $where['_string'] = 'FIND_IN_SET('.$post['uid'].',person_id)';

            $page = $post['page']>1?($post['page']-1)*$post['num']:0;
            $list = M('project')->where($where)->order('sort asc,id desc')->limit($page,$post['num'])->select();
            foreach ($list as $ks=>$vs){
                $list[$ks]['style'] = get_cate($vs['style_id']);
                $list[$ks]['house_type'] = get_cate($vs['huxing_id']);
                $list[$ks]['imgarr'] = imgarr($vs['imgarr']);
            }

            $arr = array('code'=>200,'msg'=>'成功','result'=>$list);
            exit(json_encode($arr));


        }
    }



}

